<template>
  <view class="profile-container">
    <!-- 移除原来的header部分 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px', background: 'transparent' }"></view>
    
    <!-- 功能列表 -->
    <view class="feature-list">
      <view class="feature-item" @tap="openThemePopup">
        <view class="feature-left">
          <uni-icons type="color" size="20" :color="themeColors.primary"></uni-icons>
          <text>主题设置</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="feature-item" @tap="openMusicPlayer">
        <view class="feature-left">
          <uni-icons type="headphones" size="20" color="#6E8CD5"></uni-icons>
          <text>轻音乐</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="feature-item" @tap="showEasterEgg">
        <view class="feature-left">
          <uni-icons type="gift-filled" size="20" color="#FF69B4"></uni-icons>
          <text>小惊喜</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="feature-item" @tap="showBackupMenu">
        <view class="feature-left">
          <uni-icons type="download" size="20" color="#67C23A"></uni-icons>
          <text>数据备份</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="feature-item" @tap="clearData">
        <view class="feature-left">
          <uni-icons type="trash" size="20" color="#F56C6C"></uni-icons>
          <text class="warning-text">清空数据</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="feature-item" @tap="about">
        <view class="feature-left">
          <uni-icons type="info" size="20" color="#909399"></uni-icons>
          <text>关于</text>
        </view>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 自定义的关于菜单弹窗 -->
    <uni-popup ref="aboutPopup" type="bottom">
      <view class="about-menu">
        <view class="menu-title">关于</view>
        <view class="menu-list">
          <view class="menu-item" @tap="showAppInfo">
            <text>应用介绍</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
          <view class="menu-item" @tap="checkUpdate">
            <text>版本检测</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view class="menu-cancel" @tap="hideAboutMenu">取消</view>
      </view>
    </uni-popup>

    <!-- 应用介绍弹窗 -->
    <CustomModal
      ref="appInfoModal"
      title="应用介绍"
      type="appInfo"
      version="1.0.0"
      confirmText="我知道了"
    />
    
    <!-- 版本信息弹窗 -->
    <ConfirmModal
      ref="versionModal"
      title="版本信息"
      :content="updateContent"
      confirmText="确定"
      :showCancel="false"
    />

    <!-- 清空数据确认弹窗 -->
    <ConfirmModal
      ref="confirmModal"
      title="确认清空"
      content="确定要清空所有数据吗？此操作不可恢复！"
      confirmText="确定清空"
      cancelText="取消"
      type="warning"
      @confirm="confirmClear"
    />

    <!-- 清空数据后的重启提示弹窗 -->
    <ConfirmModal
      ref="clearRestartModal"
      title="提示"
      content="您已清空数据，需要重启应用"
      confirmText="确定"
      :showCancel="false"
      @confirm="handleRestart"
    />

    <!-- 添加彩蛋弹窗 -->
    <uni-popup ref="easterEggPopup" type="center" :mask-click="false">
      <view class="easter-egg-container" :class="{ 'show-egg': showingEgg }">
        <view class="egg-content">
          <view class="egg-emoji">🎉</view>
          <view class="egg-message">{{ eggMessage }}</view>
          <view class="egg-count">已被发现 {{ discoveryCount }} 次</view>
        </view>
        <button class="egg-btn" @tap="closeEasterEgg">好的</button>
      </view>
    </uni-popup>

    <!-- 添加第二次彩蛋的特殊弹窗 -->
    <uni-popup ref="specialEggPopup" type="center" :mask-click="false">
      <view class="easter-egg-container special-egg" :class="{ 'show-egg': showingSpecialEgg }">
        <view class="egg-content">
          <view class="egg-emoji">✨</view>
          <view class="egg-message">
            <text class="special-title">解锁成就</text>
            <text class="special-desc">你已经成为了幸运的0.00001%，是否接受送的小惊喜？</text>
          </view>
        </view>
        <button class="egg-btn special-btn" @tap="closeSpecialEgg">太棒了</button>
      </view>
    </uni-popup>

    <!-- 添加备份菜单弹窗 -->
    <uni-popup ref="backupPopup" type="bottom">
      <view class="about-menu">
        <view class="menu-title">数据备份</view>
        <view class="menu-list">
          <view class="menu-item" @tap="exportData">
            <text>导出备份</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
          <view class="menu-item" @tap="importData">
            <text>导入备份</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view class="menu-cancel" @tap="hideBackupMenu">取消</view>
      </view>
    </uni-popup>

    <!-- 导入确认弹窗 -->
    <ConfirmModal
      ref="importConfirmModal"
      title="确认导入"
      content="导入新数据将覆盖当前所有数据，是否继续？ 默认最近备份导入"
      confirmText="确定导入"
      cancelText="取消"
      type="warning"
      @confirm="confirmImport"
    />

    <!-- 导入数据后的重启提示弹窗 -->
    <ConfirmModal
      ref="restartModal"
      title="提示"
      content="数据已恢复，重启应用以应用新数据"
      confirmText="确定"
      :showCancel="false"
      @confirm="handleRestart"
    />

    <!-- 版本更新确认弹窗 -->
    <ConfirmModal
      ref="updateModal"
      title="版本更新"
      :content="updateContent"
      confirmText="立即更新"
      :showCancel="false"
      @confirm="handleUpdateConfirm"
      class="version-check-modal"
    />
  </view>
</template>

<script>
import CustomModal from '@/components/CustomModal.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'

export default {
  name: 'Profile',
  props: {
    todos: {
      type: Array,
      default: () => []
    }
  },
  components: {
    CustomModal,
    ConfirmModal
  },
  computed: {
    completedCount() {
      return this.todos.filter(todo => todo.completed).length
    },
    completedRate() {
      return this.todos.length ? this.completedCount / this.todos.length : 0
    },
    themeColors() {
      return getApp().globalData.themeColors || {
        primary: '#6E8CD5',
        secondary: '#89C4F4',
        headerBg: 'linear-gradient(160deg, #89C4F4 0%, #6E8CD5 100%)'
      }
    },
    themeStyle() {
      return {
        '--primary': this.themeColors.primary,
        '--secondary': this.themeColors.secondary,
        '--background': this.themeColors.background,
        '--headerBg': this.themeColors.headerBg
      }
    }
  },
  data() {
    return {
      statusBarHeight: 0, // 添加状态栏高度变量
      showingEgg: false,
      showingSpecialEgg: false,
      discoveryCount: 0,
      eggMessages: [
        "你发现了一个小彩蛋！",
        "恭喜你以0.00001的概率触发了彩蛋", // 第二次固定显示这个
        "wow~ 你真厉害！",
        "这是一个神秘的空间~",
        "你太棒了！"
      ],
      eggMessage: "",
      updateContent: '', // 添加更新内容变量
      downloadUrl: '', // 添加下载地址变量
    }
  },
  mounted() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight
    // 获取发现次数
    this.discoveryCount = uni.getStorageSync('easterEggCount') || 0
  },
  methods: {
    openThemePopup() {
      // 获取父组件 index.vue 的实例
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      // 调用父组件的方法
      currentPage.showThemeMenu()
    },
    openMusicPlayer() {
      // // 获取父组件 index.vue 的实例
      // const pages = getCurrentPages()
      // const currentPage = pages[pages.length - 1]
      // // 调用父组件的方法
      // currentPage.showMusicPlayer()
            // 显示功能开发中的提示
        uni.showToast({
        title: '功能开发中...',
        icon: 'none',
        duration: 2000
      })
    },
    clearData() {
      this.$refs.confirmModal.show()
    },
    confirmClear() {
      uni.clearStorageSync()
      // 使用清空数据专用的重启提示
      this.$refs.clearRestartModal.show()
    },
    handleRestart() {
      // #ifdef APP-PLUS
      plus.runtime.restart()  // 使用 restart 而不是 quit，这样可以自动重启
      // #endif
      
      // #ifdef H5
      window.location.reload()
      // #endif
      
      // #ifdef MP
      uni.reLaunch({
        url: '/pages/index/index'
      })
      // #endif
    },
    about() {
      // 显示自定义菜单
      this.$refs.aboutPopup.open()
    },
    hideAboutMenu() {
      this.$refs.aboutPopup.close()
    },
    showAppInfo() {
      this.hideAboutMenu()
      this.$refs.appInfoModal.show()
    },
    checkUpdate() {
      // #ifdef APP-PLUS
      plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
        const currentVersion = widgetInfo.version
        // 使用 ConfirmModal 组件显示版本信息
        this.$refs.versionModal.show()
        this.updateContent = `当前版本：v${currentVersion}`
      })
      // #endif
    },
    handleVersionClose() {
      // 直接关闭弹窗，不做其他操作
      this.$refs.versionModal.hide()
    },
    showEasterEgg() {
      // 更新发现次数
      this.discoveryCount++
      uni.setStorageSync('easterEggCount', this.discoveryCount)
      
      // 设置消息
      if (this.discoveryCount === 2) {
        this.eggMessage = this.eggMessages[1] // 第二次固定显示
      } else {
        // 随机选择一条消息，但跳过索引1
        let availableMessages = this.eggMessages.filter((_, index) => index !== 1)
        this.eggMessage = availableMessages[Math.floor(Math.random() * availableMessages.length)]
      }
      
      // 显示弹窗和动画
      this.$refs.easterEggPopup.open()
      setTimeout(() => {
        this.showingEgg = true
      }, 100)
      
      // 触发一些彩蛋效果
      this.triggerEasterEggEffects()
    },
    
    closeEasterEgg() {
      this.showingEgg = false
      setTimeout(() => {
        this.$refs.easterEggPopup.close()
        // 如果是第二次，关闭后显示特殊弹窗
        if (this.discoveryCount === 2) {
          setTimeout(() => {
            this.showSpecialEgg()
          }, 300)
        }
      }, 300)
    },

    showSpecialEgg() {
      this.$refs.specialEggPopup.open()
      setTimeout(() => {
        this.showingSpecialEgg = true
      }, 100)
    },

    closeSpecialEgg() {
      this.showingSpecialEgg = false
      setTimeout(() => {
        this.$refs.specialEggPopup.close()
        
        // #ifdef APP-PLUS
        // 使用应用内置webview打开
        const webview = plus.webview.create('/static/surprise.html', 'surprise', {
          titleNView: {
            autoBackButton: true,
            backgroundColor: '#FFD700',
            buttons: [{
              float: 'left',
              fontSrc: '/static/uni.ttf',
              text: '\ue583', // 使用 uni-icons 的返回图标
              width: '44px',
              onclick: () => {
                webview.close('slide-out-right')
              }
            }]
          }
        })
        // 监听返回按键
        plus.key.addEventListener('backbutton', () => {
          webview.close('slide-out-right')
        })
        webview.show('slide-in-right')
        // #endif
        
        // #ifdef H5
        window.open('/static/surprise.html', '_blank')
        // #endif
        
        // #ifdef MP
        uni.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent('/static/surprise.html')}`
        })
        // #endif
      }, 300)
    },
    
    triggerEasterEggEffects() {
      // APP端不执行粒子效果
      // #ifdef H5
      const colors = ['#FF69B4', '#87CEEB', '#98FB98', '#DDA0DD', '#F0E68C']
      for (let i = 0; i < 30; i++) {
        this.createParticle(colors[Math.floor(Math.random() * colors.length)])
      }
      // #endif
    },
    
    createParticle(color) {
      // 只在H5环境下执行
      // #ifdef H5
      const particle = document.createElement('div')
      particle.className = 'particle'
      particle.style.backgroundColor = color
      particle.style.left = '50%'
      particle.style.top = '50%'
      
      document.body.appendChild(particle)
      
      const animation = particle.animate([
        {
          transform: `translate(${Math.random() * 200 - 100}px, ${Math.random() * 200 - 100}px) scale(0)`,
          opacity: 1
        },
        {
          transform: `translate(${Math.random() * 400 - 200}px, ${Math.random() * 400 - 200}px) scale(1)`,
          opacity: 0
        }
      ], {
        duration: 1000 + Math.random() * 1000,
        easing: 'cubic-bezier(0,0,0.2,1)'
      })
      
      animation.onfinish = () => particle.remove()
      // #endif
    },

    showBackupMenu() {
      this.$refs.backupPopup.open()
    },
    
    hideBackupMenu() {
      this.$refs.backupPopup.close()
    },
    
    exportData() {
      try {
        const backupData = {
          todos: uni.getStorageSync('todos') || [],
          theme: uni.getStorageSync('currentTheme')
        }
        
        const dataStr = JSON.stringify(backupData)
        
        // #ifdef APP-PLUS
        const fileName = `todo_backup_${new Date().getTime()}.json`
        const docPath = plus.io.convertLocalFileSystemURL('_doc/')
        
        plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
          fs.root.getFile(fileName, { create: true }, (fileEntry) => {
            fileEntry.createWriter((writer) => {
              writer.write(dataStr)
              uni.showToast({
                title: '备份成功',
                icon: 'success'
              })
            })
          }, (e) => {
            throw new Error(e.message)
          })
        }, (e) => {
          throw new Error(e.message)
        })
        // #endif
        
        this.hideBackupMenu()
      } catch (e) {
        uni.showToast({
          title: '备份失败',
          icon: 'error'
        })
      }
    },
    
    importData() {
      // #ifdef APP-PLUS
      const docPath = plus.io.convertLocalFileSystemURL('_doc/')
      
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
        fs.root.createReader().readEntries((entries) => {
          const backupFiles = entries.filter(entry => 
            entry.name.startsWith('todo_backup') && entry.name.endsWith('.json')
          )
          
          if (backupFiles.length === 0) {
            uni.showToast({
              title: '未找到备份文件',
              icon: 'none'
            })
            return
          }
          
          // 读取最新的备份文件
          const latestBackup = backupFiles.sort((a, b) => 
            b.name.split('_')[2].split('.')[0] - a.name.split('_')[2].split('.')[0]
          )[0]
          
          // 读取文件内容
          latestBackup.file((file) => {
            const reader = new plus.io.FileReader()
            reader.onloadend = (e) => {
              try {
                const content = e.target.result
                this.importContent = content
                this.$refs.importConfirmModal.show()
              } catch (e) {
                uni.showToast({
                  title: '读取备份失败',
                  icon: 'error'
                })
              }
            }
            reader.readAsText(file)
          })
        })
      }, (e) => {
        uni.showToast({
          title: '读取目录失败',
          icon: 'error'
        })
      })
      // #endif
      
      this.hideBackupMenu()
    },
    
    confirmImport() {
      try {
        if (!this.importContent) {
          throw new Error('没有可导入的内容')
        }
        
        const data = JSON.parse(this.importContent)
        
        // 恢复数据，不恢复彩蛋数据
        if (data.todos) uni.setStorageSync('todos', data.todos)
        if (data.theme) uni.setStorageSync('currentTheme', data.theme)
        
        this.$refs.restartModal.show()
      } catch (e) {
        uni.showToast({
          title: '导入失败',
          icon: 'error'
        })
      }
    }
  }
}
</script>

<style>
.profile-container {
  min-height: 100vh;
  background: var(--background);
  padding-bottom: env(safe-area-inset-bottom);
}

.status-bar {
  width: 100%;
}

.feature-list {
  margin-top: 20rpx; /* 调整与顶部的距离 */
  background: #FFFFFF;
  border-radius: 20rpx;
  margin-left: 30rpx;
  margin-right: 30rpx;
}

.feature-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #EEEEEE;
}

.feature-item:last-child {
  border-bottom: none;
}

.feature-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.feature-left text {
  font-size: 28rpx;
  color: #333333;
}

.warning-text {
  color: #F56C6C !important;
}

.about-menu {
  background: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
}

.menu-title {
  text-align: center;
  font-size: 32rpx;
  color: #333;
  padding: 30rpx 0;
  font-weight: 500;
}

.menu-list {
  border-top: 1rpx solid #eee;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  font-size: 30rpx;
  color: #333;
  background: #fff;
}

.menu-item:active {
  background: #f5f5f5;
}

.menu-cancel {
  text-align: center;
  padding: 30rpx;
  color: #666;
  font-size: 30rpx;
  border-top: 16rpx solid #f5f5f5;
}

.menu-cancel:active {
  background: #f5f5f5;
}

.easter-egg-container {
  background: #FFFFFF;
  border-radius: 20rpx;
  width: 560rpx;
  padding: 40rpx;
  text-align: center;
  transform: scale(0.8);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.easter-egg-container.show-egg {
  transform: scale(1);
  opacity: 1;
}

.egg-content {
  margin-bottom: 30rpx;
}

.egg-emoji {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  animation: bounce 1s infinite;
}

.egg-message {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.egg-count {
  font-size: 24rpx;
  color: #999;
}

.egg-btn {
  background: linear-gradient(45deg, #FF69B4, #87CEEB);
  color: #FFFFFF;
  border: none;
  border-radius: 40rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
}

.particle {
  position: fixed;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  pointer-events: none;
  z-index: 9999;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20rpx);
  }
}

.special-egg {
  background: linear-gradient(135deg, #FFD700, #FFA500);
}

.special-title {
  font-size: 36rpx;
  color: #FFFFFF;
  font-weight: bold;
  display: block;
  margin-bottom: 16rpx;
}

.special-desc {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  display: block;
}

.special-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.4);
}

.special-btn:active {
  background: rgba(255, 255, 255, 0.3);
}

/* 版本检测弹窗样式 */
.version-check-modal :deep(.modal-content) {
  text-align: center;
  padding: 30rpx;
  font-size: 32rpx;  /* 增大字体 */
  color: #333;  /* 使用深灰色替代绿色 */
  line-height: 2;  /* 增加行高 */
}

.version-check-modal :deep(.modal-title) {
  font-size: 36rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.version-check-modal :deep(.modal-confirm) {
  margin-top: 30rpx;
  background: #6E8CD5;  /* 使用主题色 */
  border-radius: 10rpx;
}
</style> 